<template>
  <!-- 分配权限的对话框 -->
  <el-dialog
    title="分配权限"
    v-model="setPermissionDialogVisible"
    width="50%"
    @close="setPermissionDialogClose"
  >
    <!-- 树形控件 -->
    <el-tree
      :data="permissionList"
      :props="treeProps"
      show-checkbox
      node-key="id"
      default-expand-all
      :default-checked-keys="defKeys"
      ref="treeRef"
    ></el-tree>
    <!-- 底部区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="setPermissionDialogClose">取 消</el-button>
        <el-button type="primary" @click="allotPermissions">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { setRolePermissions } from "network/role.js";
export default {
  props: {
    setPermissionDialogVisible: {
      type: Boolean,
      default: false
    },
    permissionList: {
      type: Array,
      default: []
    },
    //默认选中的节点的id数组
    defKeys: {
      type: Array,
      default: []
    },
    //角色id
    roleId: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      //属性组件的属性绑定对象
      treeProps: {
        label: "authName", //显示字段
        children: "children" //嵌套字段
      }
    };
  },
  emits: ["setPermissionDialogClose"],
  methods: {
    //监听分配权限对话框的关闭事件
    setPermissionDialogClose() {
      this.$emit("setPermissionDialogClose", false);
    },
    //监听分配节点按钮点击事件
    async allotPermissions() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      const idStr = keys.join(",");
      const res = await setRolePermissions(this.roleId, idStr);
      if (!res.success)
        return this.$message.error({ showClose: true, message: res.msg });
      this.$message.success({ showClose: true, message: res.msg });
      this.$emit("setPermissionDialogClose", true);
    }
  }
};
</script>

<style></style>
